<?php

namespace Admin;

use Application\AdminAbstract;
use Zend_Auth;
use Zend_Session;
use Zend_Session_Namespace;

class Controller extends AdminAbstract
{
    private $model;
    private $session;

    public function __construct()
    {
        parent::__construct();
        $this->model = new Model();
        Zend_Session::start();
        $this->session = new Zend_Session_Namespace(__NAMESPACE__);
        $this->session->setExpirationHops(1);
    }

    protected function getConfig()
    {
        return include(__DIR__ . '/config/module.config.php');
    }

    protected function indexAction()
    {
    }

    protected function loginAction()
    {
        $form = $this->getForm(__NAMESPACE__ . '\Form\Login');
        if ($this->isValidForm($form)) {
            $authAdapter = $this->getAuthAdapter()
                ->setIdentity($form->getValue('userName'))
                ->setCredential($form->getValue('password'));
            $auth = Zend_Auth::getInstance();
            $resultAuth = $auth->authenticate($authAdapter);
            if ($resultAuth->isValid()) {
                $user = $authAdapter->getResultRowObject();
                $user->credential = $form->getValue('password');
                $auth->getStorage()->write($user);
                $this->redirect('admin');
            } else {
                $result['errorMessage'] = 'Wrong username or password';
            }
        }
        $result['form'] = $form;
        return $result;
    }

    protected function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $auth->clearIdentity();
        }
        $this->redirect('admin/login');
    }

    protected function listAction()
    {
        $result['users'] = $this->model->getList('userName');
        if ($this->session->message) {
            $result['message'] = $this->session->message;
        }
        return $result;
    }

    protected function deleteAction()
    {
        $userDb = $this->checkUserId();
        if ($this->model->delete($userDb['id'])){
            $this->session->message = 'User "' . $userDb['userName'] . '" successfully deleted';
        } else {
            $this->session->message = 'User "' . $userDb['userName'] . '" is not deleted';
        }
        $this->redirect('admin/users');
    }

    protected function addAction()
    {
        $form = $this->getForm(__NAMESPACE__ . '\Form\Add');
        if (!$this->isValidForm($form)) {
            $result['form'] = $form;
            return $result;
        }
        $user = $form->getValues();
        unset($user['confirmPassword']);
        if ($this->model->insert($user)) {
            $this->session->message = 'User "' . $user['userName'] . '" successfully added';
        } else {
            $this->session->message = 'Unknown error. Cannot add user "' . $user['userName'] . '" to Db';
        }
        $this->redirect('admin/users');
        return false;
    }

    protected function editAction()
    {
        $form = $this->getForm(__NAMESPACE__ . '\Form\Edit');
        $userDb = $this->checkUserId();
        $form->populate(['role' => $userDb['role']]);
        $form->populate(['userName' => $userDb['userName']]);
        if (!$this->isValidForm($form)) {
            $result['form'] = $form;
            return $result;
        }
        $userForm = $form->getValues();
        unset($userForm['confirmPassword']);
        if ($editResult = $this->model->update($userDb['id'], $userForm)){
            $this->session->message = 'Data for user "' . $userDb['userName'] . '" is successfully updated';
        } else {
            $this->session->message = 'User "' . $userDb['userName'] . '" is not updated';
        }
        $this->redirect('admin/users');
        return false;
    }

    private function checkUserId()
    {
        if (!($id = $this->routeMatch->getParam('id'))) {
            $this->session->message = 'No User ID';
            $this->redirect('admin/users');
        }
        if (!($userDb = $this->model->find(['id' => $id]))) {
            $this->session->message = 'No such User';
            $this->redirect('admin/users');
        }
        return $userDb;
    }
}
